package com.yz.jdd.module.main.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseFragment;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.module.main.FilterActivity;
import com.yz.jdd.module.main.ItemOnClick;
import com.yz.jdd.module.main.adapter.OrderTypeAdapter;
import com.yz.jdd.module.main.adapter.OrdersAdapter;
import com.yz.jdd.module.main.entity.OrderTypeBean;
import com.yz.jdd.module.main.presenter.OrderContract;
import com.yz.jdd.module.main.presenter.OrderPresenter;
import com.yz.jdd.widget.MyPopupWindow;

import java.util.ArrayList;



/**
 * 订单Fragment
 */
public class OrderFragment extends BaseFragment implements OrderContract.View, ItemOnClick {

    //条件筛选
    ImageView filtrateImg;

    //POS点餐,异常等(原订单列表) ,下拉刷新
    public SmartRefreshLayout srl_main_update;
    public ExpandableListView expand_list;
    LinearLayout nodataLayout;
    LinearLayout cashier_order_nodata_layout;
    private OrdersAdapter orderExtendableListViewAdapter;
    private OrderContract.Presenter presenter;
    private TextView new_dataHint;

    // 订单类型切换
    private TextView titleOrderType;
    private Drawable drawableWhiteXia;
    private Drawable drawableWhiteShang;
    public MyPopupWindow datePopupWindow;//选择订单类型
    private View typeView;
    private ListView ordertypeListView;
    private OrderTypeAdapter typeAdapter;
    private ArrayList<OrderTypeBean> orderTypeList;

    // 收银订单列表
    public SmartRefreshLayout cashierOrderSrl_update;//下拉刷新
    public ExpandableListView cashierOrderExpand_list;
    private String orderType = "1";

    // 接收推送,是否自动刷新. 滑动未满一屏不刷新;
    private boolean isAutoRefresh = false;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);

        //title
        filtrateImg = view.findViewById(R.id.filtrate);
        typeView = View.inflate(getActivity(), R.layout.popu_order_type_list, null);
        ordertypeListView = typeView.findViewById(R.id.ordertype_list);
        titleOrderType = view.findViewById(R.id.title_order_type);
        drawableWhiteXia = getResources().getDrawable(R.mipmap.type_down);
        drawableWhiteShang = getResources().getDrawable(R.mipmap.type_up);
        titleOrderType.setText("收银订单");
        titleOrderType.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableWhiteXia, null);

        //原订单列表
        new_dataHint = view.findViewById(R.id.new_data_hint);
        nodataLayout = view.findViewById(R.id.nodata_layout);
        cashier_order_nodata_layout = view.findViewById(R.id.cashier_order_nodata_layout);
        presenter = new OrderPresenter(getActivity(), R.layout.item_order_list, this);
        srl_main_update = view.findViewById(R.id.srl_main_update);
        expand_list = view.findViewById(R.id.expand_list);

        //新收银订单
        cashierOrderSrl_update = view.findViewById(R.id.srl_cashier_order);//下拉刷新
        cashierOrderExpand_list = view.findViewById(R.id.cashier_order_expand_list);
        cashierOrderExpand_list.getHeight();
        cashierOrderExpand_list.getMeasuredHeight();
        cashierOrderExpand_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            private SparseArray recordSp = new SparseArray(0);
            private int mCurrentfirstVisibleItem = 0;

            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
              //  LogUtils.i("onScrollStateChanged: " + i);
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
             //   LogUtils.i("mCurrentfirstVisibleItem ----mCurrentfirstVisibleItem---: " + firstVisibleItem);
                mCurrentfirstVisibleItem = firstVisibleItem;
                View firstView = absListView.getChildAt(0);
                if (null != firstView) {
                    ItemRecod itemRecord = (ItemRecod) recordSp.get(firstVisibleItem);
                    if (null == itemRecord) {
                        itemRecord = new ItemRecod();
                    }
                    itemRecord.height = firstView.getHeight();
                    itemRecord.top = firstView.getTop();
                    recordSp.append(firstVisibleItem, itemRecord);
                    int h = getScrollY();//滚动距离
                    if (h > cashierOrderExpand_list.getHeight()) {
                        isAutoRefresh = false;
                    } else {
                        isAutoRefresh = true;
                    }
                    // debug
//                    LogUtils.i("滚动距离滚动距离滚动距离-------: " + h);
//                    LogUtils.i("getHeight-------: " + cashierOrderExpand_list.getHeight()); // getHeight的大小此时则是屏幕的大小
//                    LogUtils.i("getMeasuredHeight-------: " + cashierOrderExpand_list.getMeasuredHeight());  // getMeasuredHeight()是实际View的大小，与屏幕无关，
//                    WindowManager m = getActivity().getWindowManager();
//                    Display d = m.getDefaultDisplay();
//                    LogUtils.i("屏幕高度 -------: " + d.getHeight());
                }
            }

            private int getScrollY() {
                int height = 0;
                for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
                    ItemRecod itemRecod = (ItemRecod) recordSp.get(i);
                    if (itemRecod != null) {
                        height += itemRecod.height;
                    }

                }
                ItemRecod itemRecod = (ItemRecod) recordSp.get(mCurrentfirstVisibleItem);
                if (null == itemRecod) {
                    itemRecod = new ItemRecod();
                }
                return height - itemRecod.top;
            }
        });

        filtrateImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), FilterActivity.class);
                Bundle bundle = new Bundle();
                intent.putExtra("isCashList", titleOrderType.getText());
                intent.putExtra("orderType", orderType);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        // 切换订单类型
        titleOrderType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (datePopupWindow != null && datePopupWindow.isShowing()) {
                    datePopupWindow.dismiss();
                } else {
                    typePopuSelect(titleOrderType, (RelativeLayout) titleOrderType.getParent());
                }
            }
        });
        // 有新订单数据,点击刷新
        new_dataHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("收银订单".equals(titleOrderType.getText())) {
                    try {
                        cashierOrderExpand_list.smoothScrollToPosition(0);
                    } catch (Exception e) {
                        e.printStackTrace();
//                        LogBackUtil.i(e.toString());
                    }
                    cashierOrderSrl_update.autoRefresh();
                } else {
                    srl_main_update.autoRefresh();
                }
            }
        });

        srl_main_update.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                presenter.doGetOrderList(true, orderType);
            }

        });
        srl_main_update.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                presenter.doGetOrderList(false, orderType);
            }
        });

        cashierOrderSrl_update.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                presenter.doGetCashierOrderList(true);
            }

        });
        cashierOrderSrl_update.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                presenter.doGetCashierOrderList(false);
            }
        });

        initData();
        if ("收银订单".equals(titleOrderType.getText())) {
            presenter.doGetCashierOrderList(true);
        } else {
            presenter.doGetOrderList(true, orderType);
        }
        return view;
    }

    public void requestOrderList() {
        presenter.doGetOrderList(true, orderType);
    }

    public void requestCashierOrderList() {
        presenter.doGetCashierOrderList(true);
    }

    public void initData() {
        orderTypeList = new ArrayList<>();
        orderTypeList.add(new OrderTypeBean("收银订单", "1", true));
        orderTypeList.add(new OrderTypeBean("POS点餐", "2", false));
        orderTypeList.add(new OrderTypeBean("外卖订单", "3", false));
        orderTypeList.add(new OrderTypeBean("异常订单", "4", false));
    }

    @Override
    public void noMore() {
        if ("收银订单".equals(titleOrderType.getText())) {
            cashierOrderSrl_update.setNoMoreData(true);
            cashierOrderSrl_update.setEnableLoadMore(false);
        } else {
            srl_main_update.setNoMoreData(true);
            srl_main_update.setEnableLoadMore(false);
        }
    }

    @Override
    public void More() {
        if ("收银订单".equals(titleOrderType.getText())) {
            cashierOrderSrl_update.setEnableLoadMore(true);
            cashierOrderSrl_update.setNoMoreData(false);
        } else {
            srl_main_update.setEnableLoadMore(true);
            srl_main_update.setNoMoreData(false);
        }
    }

    @Override
    public void noData() {
        if (!"收银订单".equals(titleOrderType.getText())) {
            nodataLayout.setVisibility(View.VISIBLE);
        } else {
            cashier_order_nodata_layout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void Data() {
        if (!"收银订单".equals(titleOrderType.getText())) {
            nodataLayout.setVisibility(View.GONE);
        } else {
            cashier_order_nodata_layout.setVisibility(View.GONE);
        }
    }

    @Override
    public void refreshComplete(boolean isRefresh) {
        if (!"收银订单".equals(titleOrderType.getText())) {
            srl_main_update.finishRefresh();
            srl_main_update.finishLoadMore();
        } else {
            cashierOrderSrl_update.finishRefresh();
            cashierOrderSrl_update.finishLoadMore();
        }
        if (isRefresh) {
            if (new_dataHint.getVisibility() == View.VISIBLE) {
                new_dataHint.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void setSelection(int position) {
        try {
            cashierOrderExpand_list.setSelection(position);
        } catch (Exception e) {

        }
    }

    @Override
    public void setPresenter(OrderPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void setAdapter() {
        orderExtendableListViewAdapter = presenter.getAdapter();
        expand_list.setAdapter(orderExtendableListViewAdapter);

        //设置分组的监听
        expand_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true; // true为不能点击收缩：
            }
        });
        //设置子项布局监听
        expand_list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                presenter.startOrderDetail(groupPosition, childPosition, false, orderType);
                return true;

            }
        });


    }

    @Override
    public void layoutOnClick(Boolean isMore, int groupId, int childId) {
        if (isMore) {
            //加载更多
            presenter.getOrderLiuShuiList(false, groupId, true);
        } else {
            presenter.startOrderDetail(groupId, childId, true, "0"); // 跳转至详情页面
        }
    }

    @Override
    public void setCashAdapter() {
        presenter.getCashAdapter().setItemOnClick(this);
        cashierOrderExpand_list.setAdapter(presenter.getCashAdapter());
        //设置分组的监听
        cashierOrderExpand_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return false; // true为不能点击收缩：
            }
        });
    }

    @Override
    public void expandGroup(int size) {
        int groupCount = orderExtendableListViewAdapter.getGroupCount();
        for (int i = 0; i < groupCount; i++) {
            expand_list.expandGroup(i);

        }
    }

    boolean isLoad;

    @Override
    public void expandGroup(final boolean isFirst) {
        isLoad = isFirst;
        cashierOrderExpand_list.expandGroup(0);
        //设置分组的监听
        cashierOrderExpand_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                LogUtils.i("---------------------onGroupExpand------------------------------------");
                int count = cashierOrderExpand_list.getExpandableListAdapter().getGroupCount();
                for (int j = 0; j < count; j++) {
                    if (j != groupPosition) {
                        cashierOrderExpand_list.collapseGroup(j);
                    }
                }
//                // 加载选中的位置
                if (!isLoad) {
                    presenter.getOrderLiuShuiList(false, groupPosition, false);
                }
                isLoad = false;
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


    }

    /**
     * 订单类型帅选项筛选项
     *
     * @param sourceTextView
     * @param sourceSelect   //查询日期 1:收银订单 2:POS点餐 3：外卖订单 4: 异常订单
     */
    private void typePopuSelect(final TextView sourceTextView, final RelativeLayout sourceSelect) {

        datePopupWindow = new MyPopupWindow(typeView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        typeView.findViewById(R.id.dissmiss_popu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideDatePopu();
            }
        });
        typeAdapter = new OrderTypeAdapter(getActivity(), orderTypeList);
        ordertypeListView.setAdapter(typeAdapter);
        ordertypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LogUtils.i("刷新列表-----------" + orderTypeList.get(i).getTypeName());
                sourceTextView.setText(orderTypeList.get(i).getTypeName());
                for (int k = 0; k < orderTypeList.size(); k++) {
                    orderTypeList.get(k).setSelect(false);
                }
                orderTypeList.get(i).setSelect(true);
                if (i == 0) {
                    cashierOrderSrl_update.setVisibility(View.VISIBLE);
                    srl_main_update.setVisibility(View.GONE);
                    presenter.doGetCashierOrderList(true);
                } else {
                    orderType = i + "";
                    cashierOrderSrl_update.setVisibility(View.GONE);
                    srl_main_update.setVisibility(View.VISIBLE);

                    presenter.doGetOrderList(true, orderType);
                }
                hideDatePopu();
            }
        });
        datePopupWindow.setFocusable(false);
        datePopupWindow.setOutsideTouchable(false);
        datePopupWindow.setAnimationStyle(R.style.Popup);
        datePopupWindow.update();
        ColorDrawable localColorDrawable = new ColorDrawable(0);
        datePopupWindow.setBackgroundDrawable(localColorDrawable);
        datePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                sourceTextView.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        drawableWhiteXia, null);
            }
        });
        sourceTextView.setCompoundDrawablesWithIntrinsicBounds(null, null,
                drawableWhiteShang, null);
        if (!datePopupWindow.isShowing()) {
            datePopupWindow.showAsDropDown(sourceSelect);
        }
    }

    private void hideDatePopu() {
        if (datePopupWindow != null && datePopupWindow.isShowing()) {
            datePopupWindow.dismiss();
        }
    }

    public void showTips() {
        new_dataHint.setVisibility(View.VISIBLE);
        //向下移动动画
        ScaleAnimation downTranslateAnimation = new ScaleAnimation(1, 1, 0, 1);
        downTranslateAnimation.setDuration(2000);
        new_dataHint.startAnimation(downTranslateAnimation);

        //动画监听
        downTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {//向下移动动画结束
                //     topTranslateAnimation();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    @Override
    public void notifyDataSetChanged() {
        presenter.getCashAdapter().notifyDataSetChanged();
    }

    // 收到推送消息, 刷新列表
    public void newOrderRefresh() {
        showToast("您有新订单!");
        if (cashierOrderSrl_update != null && cashierOrderSrl_update.getVisibility() == View.VISIBLE) {
            if (isAutoRefresh) {
                try {
                    cashierOrderExpand_list.smoothScrollToPosition(0);
                } catch (Exception e) {
                    e.printStackTrace();
//                    LogBackUtil.i(e.toString());
                }
//                requestCashierOrderList();
                cashierOrderSrl_update.autoRefresh();
            } else {
                showTips();
            }
        }
//        else if (srl_main_update != null && srl_main_update.getVisibility() == View.VISIBLE) {
//            //非交易订单不刷新
//            try {
//                expand_list.smoothScrollToPosition(0);
//            } catch (Exception e) {
//                LogBackUtil.i(e.toString());
//            }
//            requestOrderList();
//            //     orderFragment.srl_main_update.autoRefresh();
//        }
    }


    class ItemRecod {
        int height = 0;
        int top = 0;
    }
}
